<template>
	<el-container>
		<el-header>
			<div class="left-panel">
				<el-button type="success" icon="sc-icon-download" @click="onBatchExport">导出</el-button>
			</div>
			<div class="right-panel">
				<div class="right-panel-search">
					<el-select style="width: 130px;" v-model="search.biz" clearable placeholder="选择业务类型" filterable>
						<el-option v-for="(item, key) in bizTypes" :key="key" :label="item" :value="key" />
					</el-select>
					<el-input style="width: 150px;" v-model="search.member_id" placeholder="请输入会员ID" clearable></el-input>
					<el-date-picker style="width: 150px;" v-model="search.start_time" value-format="X" type="date"
						placeholder="开始时间" />
					<el-date-picker style="width: 150px;" v-model="search.end_time" value-format="X" type="date"
						placeholder="截止时间" />
					<el-button type="primary" icon="el-icon-search" @click="upsearch">搜索</el-button>
					<el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
				</div>
			</div>
		</el-header>
		<el-main class="nopadding">
			<scTable ref="table" :apiObj="list.apiObj" row-key="id" stripe :params="tableParams" @selection-change="selectionChange">
				<el-table-column label="ID" prop="id" width="80"></el-table-column>
				<el-table-column label="会员信息" prop="member_id" width="120">
					<template #default="scope">
						<p><strong>会员ID：</strong>{{scope.row.member_id}}</p>
					</template>
				</el-table-column>
				<el-table-column label="业务类型" prop="biz" width="120">
					<template #default="scope">
						<el-tag :type="getBizTagType(scope.row.biz)">{{scope.row.biz_name}}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="金额信息" prop="amount" width="200">
					<template #default="scope">
						<p><strong>变动金额：</strong>
							<span :class="getAmountClass(scope.row.amount)">
								{{scope.row.amount > 0 ? '+' : ''}}{{scope.row.amount}}元
							</span>
						</p>
						<p><strong>变动前：</strong>{{scope.row.balance_before}}元</p>
						<p><strong>变动后：</strong>{{scope.row.balance_after}}元</p>
					</template>
				</el-table-column>
				<el-table-column label="订单号" prop="ordernum" width="200">
					<template #default="scope">
						<p><strong>订单号：</strong>{{scope.row.ordernum || '暂无'}}</p>
					</template>
				</el-table-column>
				<el-table-column label="时间" prop="create_time" width="180">
					<template #default="scope">
						<p><strong>创建时间：</strong>{{scope.row.create_time}}</p>
					</template>
				</el-table-column>
			</scTable>
		</el-main>
	</el-container>
</template>

<script>
	export default {
		name: 'balanceLogList',
		data() {
			return {
				search: {
					biz: '',
					member_id: '',
					start_time: '',
					end_time: ''
				},
				list: {
					apiObj: null
				},
				bizTypes: {
					'': '全部类型',
					'100': '充值',
					'101': '佣金提成',
					'102': '退款',
					'201': '提现',
					'202': '快递下单'
				}
			}
		},
		computed: {
			// 表格参数，避免修改原始search对象
			tableParams() {
				return {
					biz: this.search.biz,
					member_id: this.search.member_id,
					start_time: this.search.start_time,
					end_time: this.search.end_time
				}
			}
		},
		mounted() {
			// 延迟初始化，确保$API对象完全加载
			this.initAPI();
		},
		methods: {
			// 初始化API对象
			async initAPI() {
				// 等待$API对象完全初始化
				let retryCount = 0;
				const maxRetries = 10;
				
				while (retryCount < maxRetries) {
					if (this.$API && this.$API.balanceLog && this.$API.balanceLog.index) {
						break;
					}
					
					await new Promise(resolve => setTimeout(resolve, 200));
					retryCount++;
				}
				
				if (retryCount >= maxRetries) {
					console.error('$API对象初始化超时');
					this.$message.error('API初始化失败，请刷新页面重试');
					return;
				}
				
				// 设置API对象
				this.list.apiObj = this.$API.balanceLog.index;
				
				// 初始化完成，调用getInit
				this.getInit();
			},
			
			// 获取业务类型标签类型
			getBizTagType(biz) {
				const typeMap = {
					'100': 'success',    // 充值
					'101': 'warning',    // 佣金提成
					'102': 'info',       // 退款
					'201': 'danger',     // 提现
					'202': 'primary'     // 快递下单
				}
				return typeMap[biz] || 'info'
			},
			
			// 获取金额样式类
			getAmountClass(amount) {
				return amount > 0 ? 'text-success' : 'text-danger'
			},
			
			// 导出
			async onBatchExport() {
				try {
					// 显示加载状态
					this.$message.info('正在生成导出文件，请稍候...');
					
					// 准备导出参数
					let searchParams = JSON.parse(JSON.stringify(this.search));
					
					// 如果业务类型不为空，转换为数字类型
					if (searchParams.biz !== '') {
						searchParams.biz = parseInt(searchParams.biz);
					}
					
					// 如果会员ID不为空，转换为数字类型
					if (searchParams.member_id !== '') {
						searchParams.member_id = parseInt(searchParams.member_id);
					}
					
					// 调用导出API
					const res = await this.$API.balanceLog.index.get({
						...searchParams,
						is_export: 1
					});
					
					if (res.code == 200) {
						// 导出成功，下载文件
						this.$message.success('导出成功！');
						
						// 创建下载链接
						const link = document.createElement('a');
						link.href = res.data.url;
						link.download = res.data.filename || '余额变动记录.xlsx';
						link.style.display = 'none';
						document.body.appendChild(link);
						link.click();
						document.body.removeChild(link);
					} else {
						this.$message.error('导出失败：' + (res.msg || '未知错误'));
					}
				} catch (error) {
					console.error('导出失败:', error);
					this.$message.error('导出失败：' + error.message);
				}
			},
			
			// 搜索
			upsearch() {
				let searchParams = JSON.parse(JSON.stringify(this.search))
				// 如果业务类型不为空，转换为数字类型
				if (searchParams.biz !== '') {
					searchParams.biz = parseInt(searchParams.biz)
				}
				// 如果会员ID不为空，转换为数字类型
				if (searchParams.member_id !== '') {
					searchParams.member_id = parseInt(searchParams.member_id)
				}
				this.$refs.table.upData({
					...searchParams
				})
			},
			
			// 重置搜索
			resetSearch() {
				this.search = {
					biz: '',
					member_id: '',
					start_time: '',
					end_time: ''
				}
				this.upsearch()
			},
			
			// 初始化
			async getInit() {
				// 确保API对象存在
				if (!this.list.apiObj) {
					return;
				}
				
				// 等待DOM渲染完成后加载数据
				this.$nextTick(() => {
					if (this.$refs.table) {
						// 调用表格的数据加载方法
						this.$refs.table.upData();
					} else {
						// 如果表格引用不存在，尝试延迟加载
						setTimeout(() => {
							if (this.$refs.table) {
								this.$refs.table.upData();
							}
						}, 100);
					}
				});
			},
			
			// 表格选择变化
			selectionChange() {
				// 处理表格选择变化
			}
		}
	}
</script>

<style>
.right-panel-search {
	display: flex;
	align-items: center;
	gap: 12px;
}

.left-panel {
	display: flex;
	align-items: center;
	gap: 12px;
}

.el-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20px 24px;
	background: #fff;
	border-bottom: 1px solid #ebeef5;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.right-panel-search .el-select {
	margin-right: 8px;
}

.right-panel-search .el-input {
	margin-right: 8px;
}

.right-panel-search .el-button {
	border-radius: 6px;
	font-weight: 500;
}

.right-panel-search .el-button:not(.el-button--primary) {
	border-color: #dcdfe6;
	color: #606266;
}

.right-panel-search .el-button:not(.el-button--primary):hover {
	border-color: #409eff;
	color: #409eff;
}

.left-panel .el-button {
	border-radius: 6px;
	font-weight: 500;
	padding: 12px 20px;
}

.el-main {
	background: #f5f7fa;
	padding: 20px;
}

.el-table {
	border-radius: 8px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.el-table .el-tag {
	margin: 2px;
}

.text-success {
	color: #67c23a;
	font-weight: bold;
}

.text-danger {
	color: #f56c6c;
	font-weight: bold;
}
</style>
